from django.apps import apps
import os

import django

from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HopeIESystem.settings')

django.setup()

# 获取ReportManager应用的配置对象

report_manager_config = apps.get_app_config('ReportManager')

# 获取ReportManager应用中所有模型类

models = report_manager_config.get_models()

# 打印所有模型类的名称
print('{')
for model in models:
    print("'" + model.__name__ + "'", ":", model.__name__, ",")
print('}')
models = report_manager_config.get_models()

Serializedict_str = ""
Serializedict_str += 'serializer_dict={' + '\n'
for model in models:
    Serializedict_str += "'" + str(model.__name__) + "Serializer'" + ":" + str(model.__name__) + "Serializer," + "\n"
Serializedict_str += '}' + '\n'
# # 根据这些模型名在当前创建python文件 如果已经存在则跳过  文件名格式为 model_name_views.py
# 基序列化器类
models = report_manager_config.get_models()
with open('serializers.py', 'w', encoding='utf-8') as f:
    f.write(f"""
import json

from rest_framework import serializers

from .models import *

read_only = ['reviewer', 'revstatus', 'created_time', 'review_time']


# 基序列化器类
class BaseCompetitionSerializer(serializers.ModelSerializer):
    class Meta:
        fields = "__all__"
        read_only_fields = read_only  # 确保read_only是一个有效的变量或在使用前定义它

    def create(self, validated_data):
        report = super().create(validated_data)

        return report

    def update(self, instance, validated_data):
        report = super().update(instance, validated_data)

        return report
        """)
    for model in models:
        f.write(f"""
# {model.__name__}"序列化
class {model.__name__}Serializer(serializers.ModelSerializer):
    class Meta:
        model = {model.__name__}
        fields = "__all__"
        read_only_fields = read_only

    def create(self, validated_data):
        report = super().create(validated_data)
        return report

    def update(self, instance, validated_data):
        report = super().update(instance, validated_data)
        return report



        """)
# 往文件serializers.py中追加数据 不是覆盖数据重写
with open('serializers.py', 'a', encoding='utf-8') as f:
    f.write(f"""
{Serializedict_str}""")
models = report_manager_config.get_models()
modeldict_str = ""
modeldict_str += 'model_dict={' + '\n'
for model in models:
    modeldict_str += "'" + str(model.__name__) + "':" + str(model.__name__) + ",\n"
modeldict_str += '}' + '\n'
# # 根据这些模型名在当前创建python文件 如果已经存在则跳过  文件名格式为 model_name_views.py
# 往文件serializers.py中追加数据 不是覆盖数据重写
with open('models.py', 'a', encoding='utf-8') as f:
    f.write(f"""
{modeldict_str}""")
